<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;

class UploadController extends Controller
{
    public function index()
    {
        return view('upload');
    }

    public function upload(Request $request)
    {
        // 检查是否有文件上传
        if ($request->hasFile('file')) {
            $file = $request->file('file');

            // 将文件存储到 storage/app/uploads 目录
            $path = $file->store('uploads');

            // 读取中文文档内容
            $chinese_content = file_get_contents(storage_path('app/' . $path));
//            dd($chinese_content);

            // 获取目标语言
            $targetLanguage = $request->input('targetLanguage');

            // 根据目标语言设置翻译的配置
            switch ($targetLanguage) {
                case 'fr':
                    $lang = '法文';
                    break;
                default:
                    $lang = '英文';
                // 添加其他语言的翻译配置
            }

            // 使用 OpenAI API 进行翻译
            $api_key = getenv('OPENAI_API_KEY');
            //dd($api_key);
            //$endpoint = "https://api.openai.com/v1/engines/davinci-codex/completions";
            $endpoint = "https://api.openai.com/v1/engines/text-davinci-003/completions";
            $data = [
                "prompt" => "将以下内容翻译为 $lang :".$chinese_content,
                "max_tokens" => 150,
                "temperature" => 0.7
            ];



            $headers = [
                "Content-Type" => "application/json",
                "Authorization" => "Bearer " . $api_key
            ];

            $client = new Client();
            $response = $client->post($endpoint, [
                'headers' => $headers,
                'json' => $data,
            ]);

            // 处理 API 响应
            $translated_text = json_decode($response->getBody())->choices[0]->text;

            return "翻译结果: " . $translated_text;
        } else {
            return "文件上传失败";
        }
    }
}
